package top.superxuqc.loginbili.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyHttpClient {


    public String getMusic(HttpServletRequest request,String url,String keyword,int page){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        String cookies = request.getAttribute("cookies").toString();


        headers.add("Cookie",cookies);
        List<String> ua = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        url += "?keyword="+keyword+"&page="+page+"&search_type=video&tids=3";

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
        System.out.println("result====================" + response2.getBody());

        return response2.getBody();
    }

    public String post(HttpServletRequest request, String url, Map<String,String> map){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        Cookie[] cookies = request.getCookies();
        List<String> cookieList = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("DedeUserID")||
                    cookie.getName().equals("DedeUserID__ckMd5")||
                    cookie.getName().equals("SESSDATA")||
                    cookie.getName().equals("bili_jct")
            )
            cookieList.add(cookie.getName() + "=" + cookie.getValue());
        }

        headers.put("Cookie",cookieList);
        List<String> ua = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            paramMap.add(entry.getKey(),entry.getValue());
        }
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.postForEntity(url, httpEntity, String.class);
        System.out.println("result====================" + response2.getBody());

        return response2.getBody();
    }
    public String get(HttpServletRequest request, String url, Map<String,String> map){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        Cookie[] cookies = request.getCookies();
        List<String> cookieList = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("DedeUserID")||
                    cookie.getName().equals("DedeUserID__ckMd5")||
                    cookie.getName().equals("SESSDATA")||
                    cookie.getName().equals("bili_jct")
            )
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
        }

        headers.put("Cookie",cookieList);
        List<String> ua = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        url += "?";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            paramMap.add(entry.getKey(),entry.getValue());
            url +=entry.getKey()+"="+entry.getValue()+"&";
        }
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
        System.out.println("result====================" + response2.getBody());

        return response2.getBody();
    }


    public String get(String cookies, String url){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        headers.add("Cookie",cookies);
        List<String> ua = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
        System.out.println("result====================" + response2.getBody());

        return response2.getBody();
    }

    public String get(String cookies, String url, Map<String,String> map){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        headers.add("Cookie",cookies);
        List<String> ua = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();

        url += "?";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            paramMap.add(entry.getKey(),entry.getValue());
            url +=entry.getKey()+"="+entry.getValue()+"&";
        }
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
        System.out.println("result====================" + response2.getBody());

        return response2.getBody();
    }

    /**
     * 给bilibilib app api发送请求
     * @param b 有次参数时，cookie从request attribute域内获取
     * @param request
     * @param url
     * @param map
     * @return
     */
    public String get(boolean b,HttpServletRequest request, String url, Map<String,String> map){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        String cookiesApp = request.getAttribute("cookies").toString();

        headers.add("Cookie",cookiesApp);
        List<String> ua = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        url += "?";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            paramMap.add(entry.getKey(),entry.getValue());
            url +=entry.getKey()+"="+entry.getValue()+"&";
        }
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
        System.out.println("result====================" + response2.getBody());

        return response2.getBody();
    }

    public static void main(String[] args) {
        String url = "https://upos-sz-mirrorcoso1.bilivideo.com/upgcxcode/08/39/334883908/334883908_nb2-1-116.flv?e=ig8euxZM2rNcNbRanwTBhwdlhWu37bUVhoNvNC8BqJIzNbfqXBvEqxTEto8BTrNvN0GvT90W5JZMkX_YN0MvXg8gNEV4NC8xNEV4N03eN0B5tZlqNxTEto8BTrNvNeZVuJ10Kj_g2UB02J0mN0B5tZlqNCNEto8BTrNvNC7MTX502C8f2jmMQJ6mqF2fka1mqx6gqj0eN0B599M=&uipk=5&nbs=1&deadline=1621414354&gen=playurlv2&os=coso1bv&oi=2102830156&trid=3e80eaf12dc84b02ac57cdc8d8e0bd5au&platform=pc&upsig=2399fcf7dcf473346717aa86e6f8563f&uparams=e,uipk,nbs,deadline,gen,os,oi,trid,platform&mid=229162729&orderid=0,3&agrr=1&logo=80000000";

        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
        conn.setRequestProperty("referer","https://www.bilibili.com");
        conn.setRequestProperty("host","bilibili.com");
        conn.setRequestProperty("cookie","_uuid=B123C4AA-E411-D731-3414-E1E57ABF860E31827infoc; buvid3=5001AC89-EFDA-450F-B0FA-F04DCF86DE5D143074infoc; blackside_state=1; rpdid=|(J|)u|Ykm~Y0J'ulmmkk|Rll; CURRENT_FNVAL=80; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1599562100; LIVE_BUVID=AUTO6915997928313553; fingerprint3=13ad5b517372010032bee1cc3dda3864; buivd_fp=5001AC89-EFDA-450F-B0FA-F04DCF86DE5D143074infoc; buvid_fp_plain=5001AC89-EFDA-450F-B0FA-F04DCF86DE5D143074infoc; fingerprint_s=f26ae3f54b5c149f3ebce82994a3437d; buvid_fp=5001AC89-EFDA-450F-B0FA-F04DCF86DE5D143074infoc; SESSDATA=75cfe44e%2C1629897997%2C28fee%2A21; bili_jct=ea2ca524f3c6b975576664c06be0dbf0; DedeUserID=229162729; DedeUserID__ckMd5=eb33033b561ac74a; sid=bedan43a; CURRENT_QUALITY=64; bp_article_offset_229162729=523040760831507874; bp_video_offset_229162729=525764508831689492; bp_t_offset_229162729=525781306446805520; PVID=2; fingerprint=33e62c3a4fc3d1a6da0f610be737d535; bsource=search_baidu");
        conn.setRequestProperty("method","Get");
        conn.setRequestProperty("Range","bytes=0-");
        conn.setRequestProperty("accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");



        InputStream inputStream = null;
        try {
            inputStream = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(new File("D:/a11158411523.flv"));
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("出错" + e.getMessage());
            e.printStackTrace();
        }

    }





    public String getLike(HttpServletRequest request,String id){
        String url = "http://api.bilibili.com/x/web-interface/archive/related";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        Cookie[] cookies = request.getCookies();
        List<String> cookieList = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("DedeUserID")||
                    cookie.getName().equals("DedeUserID__ckMd5")||
                    cookie.getName().equals("SESSDATA")||
                    cookie.getName().equals("bili_jct")
            )
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
        }
        headers.put("Cookie",cookieList);
        List<String> ua = new ArrayList<>();
        List<String> re = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        re.add("https://www.bilibili.com");
        headers.put("referer",re);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        url += "?";
        if(id.startsWith("BV")){
            paramMap.add("bvid",id);
            url += "bvid="+id;
        }else {
            paramMap.add("aid",id);
            url +="aid="+id;
        }

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);

        return response2.getBody();
    }
    public String getLike(String id,String cookies){
        String url = "http://api.bilibili.com/x/web-interface/archive/related";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        headers.add("Cookie",cookies);
        List<String> ua = new ArrayList<>();
        List<String> re = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        re.add("https://www.bilibili.com");
        headers.put("referer",re);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        url += "?aid="+id +"&cookies="+cookies ;


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);

        return response2.getBody();
    }
    public JSONArray getTop(){

        String url = "http://api.bilibili.com/x/web-interface/ranking/region?rid=";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        int[] tID = {1,13,167,3,129,4,36,188,160,211,217,119,155,202,5,181,177,23,11};
        String[] tName = {"动画","番剧","国创","音乐","舞蹈","游戏","知识","数码","生活","美食","动物圈","鬼畜","时尚","资讯","娱乐","影视","纪录片","电影","电视剧"};
        
        List<String> ua = new ArrayList<>();
        List<String> re = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        re.add("https://www.bilibili.com");
        headers.put("referer",re);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        JSONArray tops = new JSONArray();
        for (int i = 0; i < tID.length ; i++) {
            ResponseEntity<String> response2 = restTemplate.exchange(url+tID[i], HttpMethod.GET,httpEntity,String.class);
            JSONObject top = JSONObject.parseObject(response2.getBody());
            JSONObject data;
            try {
                data = top.getJSONArray("data").getJSONObject(0);
            }catch (Exception e){
                continue;
            }

            tops.add(data);

        }

        return tops;


    }

    public String getHistory(HttpServletRequest request,String cookies){

        String url = "http://api.bilibili.com/x/web-interface/history/cursor";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        headers.add("Cookie",cookies);
        List<String> ua = new ArrayList<>();
        List<String> re = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        re.add("https://www.bilibili.com");
        headers.put("referer",re);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);

        return response2.getBody();
    }
    public String getHistory(HttpServletRequest request){

        String url = "http://api.bilibili.com/x/web-interface/history/cursor";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        Cookie[] cookies = request.getCookies();
        List<String> cookieList = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("DedeUserID")||
                    cookie.getName().equals("DedeUserID__ckMd5")||
                    cookie.getName().equals("SESSDATA")||
                    cookie.getName().equals("bili_jct")
            )
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
        }
        headers.put("Cookie",cookieList);
        List<String> ua = new ArrayList<>();
        List<String> re = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        re.add("https://www.bilibili.com");
        headers.put("referer",re);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);

        return response2.getBody();
    }
    public String down(HttpServletRequest request, String url){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        Cookie[] cookies = request.getCookies();
        List<String> cookieList = new ArrayList<>();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("DedeUserID")||
                    cookie.getName().equals("DedeUserID__ckMd5")||
                    cookie.getName().equals("SESSDATA")||
                    cookie.getName().equals("bili_jct")
            )
                cookieList.add(cookie.getName() + "=" + cookie.getValue());
        }

        headers.put("Cookie",cookieList);
        List<String> ua = new ArrayList<>();
        List<String> re = new ArrayList<>();
        ua.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        headers.put("User-Agent",ua);
        re.add("https://www.bilibili.com");
        headers.put("referer",re);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();


        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<byte[]> response2 = restTemplate.exchange(url, HttpMethod.GET,httpEntity,byte[].class);
        System.out.println("result====================" + response2.getBody());

        return "";
    }
}
